package de.homelabs.bookmarkmanager.desktop.qt.menu;

import javolution.util.FastList;

import org.springframework.stereotype.Service;

import com.trolltech.qt.QSignalEmitter;
import com.trolltech.qt.gui.QAction;
import com.trolltech.qt.gui.QMenuBar;

/**
 * class for handling all menu stuff
 * @author smirk
 *
 */
@Service(value="menuManager")
public class HMenuManager extends QSignalEmitter{

	//signals
	public Signal1<HAction> menuActionSignal = new Signal1<HAction>();
	
	//root menu as javolution List
	FastList<HMenu> rootMenu;
	
	/**
	 * constructor
	 */
	public HMenuManager(){
		this.rootMenu = new FastList<HMenu>();
	}
	
	public boolean connectMenuToMenuBar(QMenuBar menuBar){
		//loop over list
		for (FastList.Node<HMenu> n = rootMenu.head(), end = rootMenu.tail(); (n = n.getNext()) != end;) {
			menuBar.addMenu(n.getValue());				//add item to menubar
		}
		
		//return
		return true;
	}
	
	/**
	 * add a root menu entry
	 * @param rootMenuEntry
	 * @return
	 */
	public boolean addRootMenuEntry(HMenu rootMenuEntry){
		this.rootMenu.add(rootMenuEntry);
		rootMenuEntry.triggered.connect(this, "triggered(QAction)");
		return true;
	}
	
	/**
	 * adds a menu action to a menu entry
	 * 
	 * @param action
	 * @param menuKey
	 * @return boolean
	 */
	public boolean addActionToRootMenu(HAction action, String menuKey){
		//loop over list
		for (FastList.Node<HMenu> n = rootMenu.head(), end = rootMenu.tail(); (n = n.getNext()) != end;) {
			if (n.getValue().getKey().equalsIgnoreCase(menuKey)){ 	//find menuKey
				//entry found
				n.getValue().addAction(action);						//add action
				return true;
			}
		}
		
		//if we land here no menu entry is found
		return false;
	}
	
	/**
	 * removes a menu action from a menu entry
	 * 
	 * @param action
	 * @param menuKey
	 * @return boolean
	 */
	public boolean removeActionToRootMenu(HAction action, String menuKey){
		//loop over list
		for (FastList.Node<HMenu> n = rootMenu.head(), end = rootMenu.tail(); (n = n.getNext()) != end;) {
			if (n.getValue().getKey().equalsIgnoreCase(menuKey)){ 	//find menuKey
				//entry found
				n.getValue().removeAction(action);					//remove action
				return true;
			}
		}
		
		//if we land here no menu entry is found
		return false;
	}
	
	/******************
	 * signal handler *
	 ******************/
	public void triggered(QAction action){
		System.out.println("triggered: "+action.text()+", key: "+((HAction) action).getActionKey());
		menuActionSignal.emit((HAction) action);
	}
}
